package com.yq.ylmall.interceptors;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.yq.ylmall.common.utils.AuthContextUtil;
import com.yq.ylmall.common.utils.JwtUtils;
import com.yq.ylmall.model.acl.User;
import com.yq.ylmall.result.Result;
import com.yq.ylmall.result.ResultCode;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.servlet.HandlerInterceptor;
;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取请求方式
        String method = request.getMethod();
        if("OPTIONS".equals(method)) {      // 如果是跨域预检请求，直接放行
            return true ;
        }

        // 获取用户和token
        String token = request.getHeader("token");
        //token是否为空
        if (StrUtil.isEmpty(token))
        {
            responseNoLoginInfo(response) ;
            return false ;
        }
        //校验token
        if (!JwtUtils.checkAdminToken(token)){
            responseIllegalTokeInfo(response); ;
            return false ;
        }
        String jsonUser = request.getHeader("jsonUser");
        User user = JSON.parseObject(jsonUser, User.class);
        AuthContextUtil.set(user);
        // 放行
        return true ;
    }
    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> loginAuth = Result.build(null, ResultCode.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(loginAuth));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }

    //响应401状态码给前端
    private void responseIllegalTokeInfo(HttpServletResponse response) {
        Result<Object> tokenAuth = Result.build(null, ResultCode.ILLEGAL_TOKEN);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(tokenAuth));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();  // 移除threadLocal中的数据
    }

}
